<template>
	<view class="userWaitDriver_container">
		<view>
			<u-navbar title="等待司机" :autoBack="true" placeholder>
			</u-navbar>
		</view>
		<!-- 滚动通知区域 -->
		<view>
			<u-notice-bar :text="ScrollText"></u-notice-bar>
		</view>
		<!-- 显示地图区域 -->
		<view class="map_navigation">
			<!-- 标记点 ：  markers -->
			<map id="navMap" class="map" enable-traffic="true" enable-poi="true" enable-scroll="true"
				:polyline="polyline" :markers="initialPoint">
			</map>
			<!-- 雨水 -->
			<canvas canvas-id="effect" id="effect"></canvas>
		</view>
		<!-- 安全提示 -->
		<u-popup :show="maskShow" :round="10" mode="center">
			<view>
				<u-modal :show="securityShow" @confirm="confirmBtn">{{content}}</u-modal>
			</view>
		</u-popup>
		<!-- 取消订单 -->
		<view class="cancelBtnBox">
			<u-button type="primary" :disabled="cancelBtn" @click="cancelCallBtn">取消叫车</u-button>
		</view>
		<!-- 司机信息 -->
		<view class="dirver">
			<!-- 左侧的司机头像与电话尾号 -->
			<view class="driverImg">
				<view class="driverInfo">
					<!-- 司机头像 -->
					<image :src="driverImg" mode="aspectFit"></image>
					<!-- 司机信息 -->
					<view class="driverPhone">{{ driverName | nameHide }}</view>
					<view class="driverPhone">{{ tel | telHide }}</view>
				</view>
			</view>
			<!-- 司机车型与车牌号 -->
			<view class="driverCard">
				<view class="licensePlate">
					<image src="../../static/Accord.png" mode="aspectFit"></image>
					<view class="driverNum">
						<text>车牌号:</text><text style="font-size: 18px;">{{ driverCarNum }}</text>
					</view>
					<view class="relationDriver">
						<image @click="call" src="../../static/tel.png" class="relationImg"></image>
						<image @click="chat" src="../../static/cancel-kefu.png" class="relationImg"></image>
					</view>
				</view>
			</view>
		</view>
		<!-- 提示用户路程已结束 -->
		<u-modal @confirm="tipsConfirmBtn" :show="Pathshow" :zoom="false" :title="pathTitle" :content='userTipscontent'>
		</u-modal>
		<!-- 提示取消叫车会影响信誉 -->
		<u-modal @confirm="tipsUserreputationBtn" showCancelButton @cancel="reputationshow = false"
			:show="reputationshow" :zoom="false" :title="pathTitle" :content='tipsUserreputation'>
		</u-modal>
		<!-- 提示订单的 -->
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import amap from "../../common/amap-wx.130.js"
	import {
		mapState,
		mapMutations
	} from 'vuex'

	import {
		trendsPath
	} from '../../common/utils.js'

	import Particle from '@/common/effect.js'


	export default {
		data() {
			return {
				navMap: '', // 初始实例化地图对象
				amapPlugin: null, // 插件效果
				gaodeKey: "4412f1a1546136b8476c2c1011cbbad9", //  高德地图申请的key
				ScrollText: "欢迎来到滴滴打车平台~", //滚动区域
				maskShow: true, //遮罩层 显示弹出
				content: '前往出发点等待司机，注意安全',
				securityShow: true, //控制安全提示---模态框的显示与隐藏
				//  初始点(用户的初始位置)
				initialPoint: [{
					id: 0,
					latitude: '',
					longitude: '',
					iconPath: "../../static/Car.png",
					width: 40,
					height: 40
				}],
				polyline: [], //路线的规划
				Rain: null, //雨水--class
				with: 0, //宽
				height: 0, //高
				scale: 0, //屏幕宽度
				ctx: null, //控制雨水插件
				rain: null, //控制雨水的动画
				distance: '', //距离
				minute: '', //分钟
				driverStart: '', //司机出发地----终点
				userEnd: '', //用户定位的目的地---起点
				points: [], // 缩放视野---记录起点和终点
				carNum: 0, //次数
				tel: '', //司机电话
				driverName: '', //司机姓名
				driverImg: '', //司机头像
				driverCarNum: '', //司机车牌号
				Pathshow: false, //控制提示用户路程结束
				userTipscontent: '路程已结束，请支付费用', //提示内容
				pathTitle: '提示', //提示标题
				reputationshow: false, //提示   用户取消叫车显示与隐藏
				tipsUserreputation: '此操作会响应您的信誉', //取消叫车提示
				finishPath: false, //用户停止叫车
				cancelBtn: false, //取消叫车按钮
			}
		},
		computed: {
			...mapState('userInfo', ['orderInfo']),
			...mapState('userLocation', ['weather']),
		},
		onLoad() {
			// 高德地图sdk的获取
			this.amapPlugin = new amap.AMapWX({
				key: this.gaodeKey
			})
			// 实例化地图对象
			this.navMap = uni.createMapContext("navMap", this)

			console.log('订单信息++++++', this.orderInfo)


			// console.log('用户订单的出发点与目的地', this.orderInfo.route, 98)

			// 司机出发地---起点
			this.driverStart = this.orderInfo.points
			console.log(this.driverStart, 156)

			// 用户的定位的目的地--终点
			this.userEnd = JSON.parse(this.orderInfo.originLatLong)
			console.log(this.userEnd, 160)

			// 拿到 markers
			// this.getLocation()

			// 司机的位置
			this.initialPoint[0] = {
				id: 0,
				latitude: this.driverStart.latitude,
				longitude: this.driverStart.longitude,
				iconPath: "../../static/Car.png",
				width: 40,
				height: 40
			}
			// 用户 定位的起点
			this.initialPoint[1] = {
				id: 1,
				longitude: this.userEnd.longitude,
				latitude: this.userEnd.latitude,
				iconPath: "../../static/起点.png",
				width: 40,
				height: 40
			}

			// 存入开始与结束的经纬度
			this.points.push(this.driverStart, this.userEnd)

			// 绘制路线
			this.amapPlugin.getDrivingRoute(this.getDataObj())

			// this.amapPlugin.getDrivingRoute(trendsPath(this.points, this))

			// 缩放地图
			this.navMap.includePoints({
				padding: [100],
				points: this.points
			})

			// 雨水效果
			this.Rain = Particle.Particle
			// 获取手机大小
			uni.getSystemInfo({
				success: res => {
					this.with = res.windowWidth
					this.scale = this.with / 375
				}
			})
			// 控制雨水动画
			this.ctx = uni.createCanvasContext('effect')
			this.height = 768 / 2 * this.scale
			this.rain = new this.Rain(this.ctx, this.with, this.height, {
				amount: 100,
				speedFactor: 0.03
			})
		},
		onShow() {
			this.getmsg()
			console.log('等待司机来的路上的天气', this.weather)
			if (this.weather == '大雨' || this.weather == '小雨' || this.weather == '中雨' || this
				.weather == '强降雨' || this
				.weather == '连续降雨') {
				// 开始下雨
				this.rain.run()
			} else {
				// 停止下雨
				this.rain.clear()
			}

			// 头像
			this.driverImg = this.orderInfo.driverPhoto
			// 姓名
			this.driverName = this.orderInfo.driverName.toString()
			// 司机ID
			this.name = this.orderInfo.name
			// 司机电话
			this.tel = this.orderInfo.userTel.toString()
			// 车牌号
			this.driverCarNum = this.orderInfo.CarNum
		},
		methods: {
			...mapMutations('userLocation', ['getEnd']),
			getmsg() {
				this.socket.on('arriverDriver', message => {
					// 收到司机到达的信息
					console.log('收到司机到达的信息', message)

					// 司机到达目的地--不可以再取消订单
					this.cancelBtn = true

					// 提示用户司机已到达
					this.content = '我已到达目的地，请尽快上车'
					this.securityShow = true
					this.maskShow = true
					// 更换地址路线
					this.points = JSON.parse(message.route)
					console.log(this.points, '新路线', 246)


					this.initialPoint = []
					this.initialPoint[0] = {
						id: 0,
						longitude: this.points[0].longitude,
						latitude: this.points[0].latitude,
						iconPath: "../../static/Car.png",
						width: 40,
						height: 40
					}
					this.initialPoint[1] = {
						id: 1,
						longitude: this.points[1].longitude,
						latitude: this.points[1].latitude,
						iconPath: "../../static/终点.png",
						width: 40,
						height: 40
					}

					// 缩放地图
					this.navMap.includePoints({
						padding: [100],
						points: this.points
					})

					//开始执行 订单路线
					this.amapPlugin.getDrivingRoute(trendsPath(this.points, this))

				})
				// 通知订单已完成
				this.socket.on('completeorder', message => {
					// 订单完成
					console.log('订单完成', message, 233)
					this.Pathshow = true
				})
				// 通知乘客订单取消---跳转首页---重新下单
				this.socket.on('cancelOrder_user', message => {
					this.getEnd('')
					uni.$showMsg('司机取消订单')
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/home/home'
						})
					}, 2000)
				})
			},
			// 安全提示---确定按钮
			confirmBtn() {
				this.securityShow = false
				this.maskShow = false
			},
			// 获取用户自己的经纬度
			// getLocation() {
			// 	uni.getLocation({
			// 		type: 'gcj02',
			// 		geocode: true,
			// 		success: res => {
			// 			// 司机的位置
			// 			this.initialPoint[0].latitude = this.driverStart.latitude
			// 			this.initialPoint[0].longitude = this.driverStart.longitude
			// 			// 用户 定位的起点
			// 			this.initialPoint[1] = {
			// 				id: 1,
			// 				longitude: this.userEnd.longitude,
			// 				latitude: this.userEnd.latitude,
			// 				iconPath: "../../static/起点.png",
			// 				width: 40,
			// 				height: 40
			// 			}
			// 		},
			// 		fail(err) {
			// 			console.log(err, '报错了')
			// 		}
			// 	})
			// },
			getDataObj() {
				if (this.finishPath) {
					console.log('司机在路上停止叫车')
					return
				}
				let color = '#0091ff'
				return {
					// 起点
					origin: this.driverStart.longitude + ',' + this.driverStart.latitude,
					// 终点
					destination: this.userEnd.longitude + ',' + this.userEnd.latitude,
					success: data => {
						console.log(data, '驾车的路线')
						this.distance = (data.paths[0].distance / 1000).toFixed(1)
						this.minute = Math.ceil(data.paths[0].duration / 60)
						// 驾车的路线
						let points = []
						if (!data || !data.paths || !data.paths[0] || !data.paths[0].steps) {
							uni.$showMsg('查询失败')
							return
						}
						let steps = data.paths[0].steps
						steps.forEach(item => {
							let polylines = item.polyline.split(';')
							polylines.forEach(item1 => {
								let locations = item1.split(',')
								points.push({
									longitude: locations[0],
									latitude: locations[1]
								})
							})
						})
						// 路线的规划
						this.polyline = [{
							points,
							color,
							width: 3
						}]


						if (this.polyline[0].points.length > 9) {
							// 改变起点
							this.points[0].longitude = this.polyline[0].points[8].longitude
							this.points[0].latitude = this.polyline[0].points[8].latitude
						} else if (this.polyline[0].points.length > 2) {
							// 改变起点
							this.points[0].longitude = this.polyline[0].points[2].longitude
							this.points[0].latitude = this.polyline[0].points[2].latitude
						} else if (this.polyline[0].points.length == 2) {
							this.carNum++
							// 改变起点
							this.points[0].longitude = this.polyline[0].points[1].longitude
							this.points[0].latitude = this.polyline[0].points[1].latitude
							if (this.carNum == 2) {
								console.log('司机到达')
								this.initialPoint[0] = {
									id: 0,
									longitude: this.polyline[0].points[0].longitude,
									latitude: this.polyline[0].points[0].latitude,
									iconPath: "../../static/Car.png",
									width: 40,
									height: 40
								}
								this.carNum = 0
								return
							}
						}
						// 改起点的坐标
						this.timeOut = setTimeout(() => {
							this.initialPoint[0] = {
								id: 0,
								longitude: this.polyline[0].points[0].longitude,
								latitude: this.polyline[0].points[0].latitude,
								iconPath: "../../static/Car.png",
								width: 40,
								height: 40
							}
							// 重新规划
							console.log('重新规划---395')
							this.amapPlugin.getDrivingRoute(this.getDataObj())
						}, 500)
					},
					// 获取路线失败
					fail(info) {
						console.log('获取失败', info)
					}
				}
			},
			// 拨打司机电话
			call() {
				uni.makePhoneCall({
					phoneNumber: this.tel
				})
			},
			// 取消叫车
			cancelCallBtn() {
				this.reputationshow = true
			},
			// 确定前往支付界面
			tipsConfirmBtn() {
				this.Pathshow = false
				uni.redirectTo({
					url: '/subpkg/overPath/overPath'
				})
			},
			// 发送请求--取消叫车
			async tipsUserreputationBtn() {
				// 停止规划路线的方法---司机在接送的路上
				this.finishPath = true
				// 停止定时器
				clearTimeout(this.timeOut)
				// 清空仓库的地址
				this.getEnd('')

				// 扣分---请求
				const pointsResult = await this.$http('/points', this.orderInfo, "POST")
				if (pointsResult.code !== 200) return console.log('扣除信誉积分失败')

				// 改变订单状态---取消订单
				const result = await this.$http('/userPlanOrder', this.orderInfo, "POST")
				if (result.code == 200) {
					// 提示
					this.$refs.uToast.show({
						type: 'success',
						message: result.data.message,
						iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png'
					})
					// 通知接驾司机
					this.socket.emit('callDriver', this.orderInfo)
				}
				// 返回首页
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/home/home'
					})
				}, 1000)
			},
			chat() {
				let userChat = {
					userId: this.name + 'driver',
					UserFace: this.driverImg,
					userName: this.driverName,
					chat: '打车'
				}
				uni.setStorageSync('userChat', userChat)
				uni.navigateTo({
					url: "/pages/chat/chat"
				})
			},
		},
		watch: {
			carNum(newValue) {
				if (newValue == 2) {
					console.log('路程已结束')
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.map_navigation {
		width: 95%;
		height: 600rpx;
		border: 1px solid #F2F5FA;
		border-radius: 10px;
		margin: 5px auto;
		position: relative;

		.map {
			width: 100%;
			height: 100%;
			border-radius: 20px;
		}

		#effect {
			// border: 1px solid red;
			width: 100%;
			height: 100%;
			border-radius: 20px;
			position: absolute;
			top: 0%;
		}
	}

	.cancelBtnBox {
		margin-top: 5px;
	}

	.dirver {
		width: 100%;
		height: 200px;
		display: flex;
		justify-content: space-between;
		padding-left: 20px;
		margin-top: 10px;
		padding-right: 20px;
		box-sizing: border-box;

		.driverImg {
			width: 50%;
			height: 100%;
			display: flex;
			align-items: center;
			margin-right: 5px;
			box-sizing: border-box;

			.driverInfo {
				width: 100%;
				height: 130px;
				display: flex;
				flex-direction: column;
				align-items: center;
				box-sizing: border-box;

				image {
					width: 100px;
					height: 100px;
					margin-top: 5px;
					// margin-bottom: 5px;
					box-sizing: border-box;
				}

				.driverPhone {
					width: 100%;
					padding-left: 10px;
					box-sizing: border-box;
					margin-top: 10px;
					text-align: center;
				}
			}
		}

		.driverCard {
			width: 60%;
			height: 100%;

			.licensePlate {
				display: flex;
				flex-direction: column;
				align-items: center;
				height: 100%;

				image {
					margin-top: 10px;
					height: 100px;
					width: 80%;
				}

				.driverNum {
					width: 100%;
					display: flex;
					align-items: center;
					padding-left: 10px;
					box-sizing: border-box;
					justify-content: center;
					margin-bottom: 8px;

					text {
						margin-right: 5px;
					}
				}

				.relationDriver {
					width: 50%;
					height: 50px;
					display: flex;
					align-items: center;
					justify-content: space-between;
				}

				.relationImg {
					margin-top: 0px;
					width: 30px;
					height: 80%;
				}
			}
		}
	}

	/deep/ .u-modal__content__text {
		font-size: 20px;
		text-align: center;
	}

	.payView {
		height: 120px;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		box-sizing: border-box;
		padding-left: 20px;

		.payView_way {
			width: 140rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: space-around;
			height: 70%;
			margin-right: 20px;
		}

		image {
			width: 50px;
		}
	}
</style>
